package com.example.composetest

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.composetest.ui.theme.ComposetestTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            ComposetestTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    ProfileView(Modifier.padding(innerPadding))
                }
            }
        }
    }
}

@Composable
fun ProfileView(modifier: Modifier, viewModel: ProfileViewModel = viewModel()) {
    val state: ProfileState by viewModel.state.collectAsStateWithLifecycle()

    when (val newState = state) {
        is ProfileState.Loading -> {
            Box(modifier = Modifier.size(48.dp)) {
                CircularProgressIndicator()
            }
        }

        is ProfileState.LoadFinished -> {
            LazyColumn(
                modifier = Modifier
                    .then(modifier)
                    .fillMaxSize()
            ) {
                item {
                    Button(onClick = {}) { Text("button") }
                }
                items(
                    newState.list
                ) {
                    Text("Text -> ${it}")
                }
            }
        }

        is ProfileState.Hidden -> {}

    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    ComposetestTheme {
        Greeting("Android")
    }
}